''' Copyright 2013 Mike Henrey 

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
GNU General Public License for more details.

You should have received a copy of the GNU General Public License along 
with this program.  If not, see <http://www.gnu.org/licenses/>.

'''

#!/usr/bin/env python

import argparse
import struct
import sys


def hex_to_raw_bytes(hexdata):
	bytes = []
  	for piece in hexdata.split():
    		print piece
    		part = struct.pack("B", int(piece, base=16))
    		bytes.append(part)

  	return ''.join(bytes)

def main(argv):
    parser = argparse.ArgumentParser(description='Convert txt to jpg')
    parser.add_argument('nFiles', metavar='N', type=int, help='number of files to process')
    parser.add_argument('inFile', help='base name of the input file')
    parser.add_argument('outFile', help='base name of the output file')

    args = parser.parse_args()
    print(args)

#    if len(args) != 4:
#        parser.error("incorrect number of arguments")

#    print args[1]
#    print args[2]
#    print args[3]

    for i in range(0,args.nFiles):
        if i < 10:
            infile = open(args.inFile+"00"+str(i)+".txt")
            outfile = open(args.outFile+"00"+str(i)+".jpg", 'w')
        elif i < 100:
            infile = open(args.inFile+"0"+str(i)+".txt")
            outfile = open(args.outFile+"0"+str(i)+".jpg", 'w')
        else:
            infile = open(args.inFile+str(i)+".txt")
            outfile = open(args.outFile+str(i)+".jpg", 'w')
        
        outfile.write(hex_to_raw_bytes(infile.read()))

        infile.close()
        outfile.close()

if __name__ == "__main__":
    sys.exit(main(sys.argv))
